package com.wlgc.service.impl;

import com.wlgc.dao.UserDao;
import com.wlgc.entity.RestBean;
import com.wlgc.service.StudentService;
import com.wlgc.service.UserService;
import com.wlgc.service.VerifyAndRegisterService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Service
public class VerifyAndRegisterServiceImpl implements VerifyAndRegisterService {
    @Resource
    UserDao dao;
    @Resource
    JavaMailSender sender;
    @Resource
    StringRedisTemplate template;
    @Resource
    StudentService studentService;
    @Resource
    UserService userService;
    @Value("${spring.mail.username}")
    String fromUsername;

    public RestBean sendVerifyCode(String email,String refer) {
        if (studentService.getStudentEmailByEmail(email).isEmpty())
            return new RestBean(500,"请输入你的通知群的QQ邮箱");
        if (!ObjectUtils.isEmpty(userService.getUserByEmail(email))&&refer.equals("1"))
            return new RestBean<>(400,"该邮箱已注册，请到登陆页面修改账号密码");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("你的验证码是");
        message.setFrom(fromUsername);
        Random random = new Random();
        int code = random.nextInt(899999) + 100000;
        message.setText("您收到到的验证码为:" + code + "，三分钟后失效，请及时注册！");
        template.opsForValue().set(email + ":VerifyCode:", code + "", 3, TimeUnit.MINUTES);
        message.setTo(email);
        sender.send(message);
        return new RestBean<>(200,"验证码已发至您的邮箱！");
    }

    @Override
    public boolean verify(String email, String code) {
        String c = template.opsForValue().get(email+":VerifyCode:");
        if (c == null)
            return false;
        return c.equals(code);
    }
}
